package com.example.myapplication;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.example.myapplication.logs.BrowseEvent;
import com.example.myapplication.logs.ChatMessage;
import com.example.myapplication.logs.LogDao;
import com.example.myapplication.logs.LogDatabase;
import com.example.myapplication.logs.PowerEvent;

import java.util.ArrayList;
import java.util.List;

/**
 * 设备数据收集器
 * 统一收集所有设备信息
 */
public class DeviceDataCollector {
    
    private static final String TAG = "DeviceDataCollector";
    
    private final Context context;
    private final DeviceDataConfig config;
    private final SystemControlService systemControlService;
    private final DevicePowerInfoService devicePowerInfoService;
    private final AppUsageService appUsageService;
    private final LogDao logDao;
    
    public DeviceDataCollector(Context context) {
        this.context = context.getApplicationContext();
        this.config = new DeviceDataConfig(context);
        this.systemControlService = new SystemControlService(context);
        this.devicePowerInfoService = new DevicePowerInfoService(context);
        this.appUsageService = new AppUsageService(context);
        this.logDao = LogDatabase.get(context).logDao();
    }
    
    /**
     * 收集所有设备数据
     * @return 设备数据模型
     */
    public DeviceDataModel collectAllData() {
        DeviceDataModel data = new DeviceDataModel();
        
        try {
            // 设置基本信息
            setBasicInfo(data);
            
            // 收集系统信息
            collectSystemInfo(data);
            
            // 收集设备电源信息
            collectPowerInfo(data);
            
            // 收集应用使用统计
            collectAppUsageStats(data);
            
            // 收集日志数据
            collectLogData(data);
            
            // 设置时间戳
            data.setTimestamp(System.currentTimeMillis());
            
        } catch (Exception e) {
            Log.e(TAG, "收集设备数据失败", e);
        }
        
        return data;
    }
    
    /**
     * 设置基本信息
     */
    private void setBasicInfo(DeviceDataModel data) {
        // 设备ID
        data.setDeviceId(config.getDeviceId());
        
        // 设备型号和Android版本
        data.setDeviceModel(android.os.Build.MODEL);
        data.setAndroidVersion(android.os.Build.VERSION.RELEASE);
        data.setApiLevel(android.os.Build.VERSION.SDK_INT);
        
        // 应用版本信息
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            data.setAppVersion(packageInfo.versionName);
            data.setAppVersionCode(packageInfo.versionCode);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "获取应用版本信息失败", e);
            data.setAppVersion("未知");
            data.setAppVersionCode(0);
        }
    }
    
    /**
     * 收集系统信息
     */
    private void collectSystemInfo(DeviceDataModel data) {
        try {
            SystemControlService.SystemInfo systemInfo = systemControlService.getSystemInfo();
            
            data.setScreenOn(systemInfo.isScreenOn);
            data.setTotalMemory(systemInfo.totalMemory);
            data.setAvailableMemory(systemInfo.availableMemory);
            data.setMemoryUsagePercent(systemInfo.memoryUsagePercent);
            data.setHasRootPermission(systemInfo.hasRootPermission);
            data.setSystemUptime(systemInfo.systemUptime);
        } catch (Exception e) {
            Log.e(TAG, "收集系统信息失败", e);
        }
    }
    
    /**
     * 收集设备电源信息
     */
    private void collectPowerInfo(DeviceDataModel data) {
        try {
            DevicePowerInfoService.DevicePowerInfo powerInfo = devicePowerInfoService.getDevicePowerInfo();
            
            data.setBootTime(powerInfo.bootTime);
            data.setCurrentTime(powerInfo.currentTime);
            data.setBatteryLevel(powerInfo.batteryLevel);
            data.setIsCharging(powerInfo.isCharging);
        } catch (Exception e) {
            Log.e(TAG, "收集电源信息失败", e);
        }
    }
    
    /**
     * 收集应用使用统计
     */
    private void collectAppUsageStats(DeviceDataModel data) {
        try {
            if (appUsageService.hasUsageStatsPermission()) {
                List<AppUsageInfo> appUsageList = appUsageService.getTodayAppUsage();
                
                List<DeviceDataModel.AppUsageData> appUsageDataList = new ArrayList<>();
                for (AppUsageInfo appUsage : appUsageList) {
                    DeviceDataModel.AppUsageData appData = new DeviceDataModel.AppUsageData();
                    appData.setPackageName(appUsage.getPackageName());
                    appData.setAppName(appUsage.getAppName());
                    appData.setTotalTime(appUsage.getTotalTimeInForeground());
                    appData.setLastUsedTime(appUsage.getLastTimeUsed());
                    appUsageDataList.add(appData);
                }
                
                data.setAppUsageStats(appUsageDataList);
            }
        } catch (Exception e) {
            Log.e(TAG, "收集应用使用统计失败", e);
        }
    }
    
    /**
     * 收集日志数据
     */
    private void collectLogData(DeviceDataModel data) {
        try {
            // 收集最近的电源事件（最近24小时）
            List<PowerEvent> powerEvents = logDao.getRecentPower();
            List<DeviceDataModel.PowerEventData> powerEventDataList = new ArrayList<>();
            for (PowerEvent event : powerEvents) {
                DeviceDataModel.PowerEventData powerData = new DeviceDataModel.PowerEventData();
                powerData.setTimestamp(event.timestamp);
                powerData.setType(event.type);
                powerEventDataList.add(powerData);
            }
            data.setRecentPowerEvents(powerEventDataList);
            
            // 收集最近的浏览记录（最近24小时）
            List<BrowseEvent> browseEvents = logDao.getRecentBrowse();
            List<DeviceDataModel.BrowseEventData> browseEventDataList = new ArrayList<>();
            for (BrowseEvent event : browseEvents) {
                DeviceDataModel.BrowseEventData browseData = new DeviceDataModel.BrowseEventData();
                browseData.setTimestamp(event.timestamp);
                browseData.setUrl(event.url);
                browseData.setTitle(event.title);
                browseEventDataList.add(browseData);
            }
            data.setRecentBrowseEvents(browseEventDataList);
            
            // 收集最近的聊天消息（最近24小时）
            List<ChatMessage> chatMessages = logDao.getRecentChat();
            List<DeviceDataModel.ChatMessageData> chatMessageDataList = new ArrayList<>();
            for (ChatMessage message : chatMessages) {
                DeviceDataModel.ChatMessageData chatData = new DeviceDataModel.ChatMessageData();
                chatData.setTimestamp(message.timestamp);
                chatData.setContent(message.content);
                chatData.setTopic(message.topic);
                chatMessageDataList.add(chatData);
            }
            data.setRecentChatMessages(chatMessageDataList);
            
        } catch (Exception e) {
            Log.e(TAG, "收集日志数据失败", e);
        }
    }
    
    /**
     * 获取配置对象
     */
    public DeviceDataConfig getConfig() {
        return config;
    }
}

